package com.qf.face.util;


import com.baidu.aip.face.AipFace;
import com.baidu.aip.face.MatchRequest;
import com.qf.base.utils.FileBase64Util;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class BaiduUtil {
    //三个 APP_ID  API_KEY  SECRET_KEY
    public static final  String APP_ID="23920996";
    public static final  String API_KEY="eWIU2L6cvH3maYcycn4QwFiS";
    public static final  String SECRET_KEY="AlohaShI44QZwi1Kfz5fPK4YPSH0b5G4";
    //初始化一个AipFace
    //百度封装的人脸识别的核心对象
    public static AipFace client=new AipFace(APP_ID,API_KEY,SECRET_KEY);

    /**判断两个人是不是同一个人
     * @Author 67517
     * @Description //TODO
     * @Param [face1FileName, face2FileName] 第一个人的人脸，第二个人的人脸
     * @return boolean
     */
    public static boolean isOne(String face1,String face2,int type)  {
        //拿到两张图片的base64
        String image1=null;
        String image2=null;
        if (type==0){
            image1=face1;
            image2=face2;
        }else if (type==1){
            //拿到两张图片的base64
             image1 = FileBase64Util.image2Base64(face1);
             image2 = FileBase64Util.image2Base64(face2);
        }
        //设置请求百度服务器的参数图片
        MatchRequest req1=new MatchRequest(image1,"BASE64");
        MatchRequest req2=new MatchRequest(image2,"BASE64");
        //把图片放入集合
        List<MatchRequest> requests=new ArrayList<>();
        requests.add(req1);
        requests.add(req2);
        //把集合交给百度
        JSONObject res = client.match(requests);
        /**
         * {
         *   "result": {
         *     "score": 95.07212067,
         *     "face_list": [
         *       {"face_token": "4cf07554dd321a28844dc581d8c7df5a"},
         *       {"face_token": "2c785248e8ad59b7fa09a926d751ed93"}
         *     ]
         *   },
         *   "log_id": 17545201752,
         *   "error_msg": "SUCCESS",
         *   "cached": 0,
         *   "error_code": 0,
         *   "timestamp": 1617329363
         * }
         */
        try {
            if ("SUCCESS".equals(res.getString("error_msg"))){
                double sc = res.getJSONObject("result").getDouble("score");
                System.out.println(sc);
                if (sc>=90) {
                    return true;
                }else {
                    return false;
                }

            }
        } catch (JSONException e) {
            e.printStackTrace();
            System.out.println("isOne方法出现错误");
        }
//        System.out.println(res.toString(2));
        return false;
    }

    /**
     * 注册人脸，把人脸文件保存至百度服务器上的人脸库
     * @param face  人脸信息
     * @param uid   用户的id
     * @param type  人脸的格式 0-base64 1-fileName
     */
    public static void saceFace(String face,String uid,int type)  {
        HashMap<String,String> options=new HashMap<>();
        options.put("action_type", "REPLACE");
        String image=null;
        if (type==0){
            image=face;
        }else if (type==1) {
            image = FileBase64Util.image2Base64(face);
        }

        String imageType="BASE64";
        String groupId="Java2003";
        String userId=uid;
        JSONObject res=client.addUser(image,imageType,groupId,userId,options);
        try {
            System.out.println(res.toString(2));
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    /**
     * 人脸搜索的地方
     * @param face  人脸信息
     * @param type  人脸的格式   0-base64 1-fileName
     * @return
     * @throws
     */
    public static Long whoAreYou(String face,int type)  {
        HashMap<String,String>options=new HashMap<>();
        String image=null;
        if (type==0){
            image=face;
        }else {
            image=FileBase64Util.image2Base64(face);
        }
        String imageType="BASE64";
        String groupIdList="Java2003";
        //人脸搜索
        /**
         * {
         *   "result": {
         *     "face_token": "cd0a881bb9e901dc0613970ae411a1c7",
         *     "user_list": [{
         *       "score": 93.64924621582,
         *       "group_id": "java2003",
         *       "user_id": "user3",
         *       "user_info": ""
         *     }]
         *   },
         *   "log_id": 7935001552011,
         *   "error_msg": "SUCCESS",
         *   "cached": 0,
         *   "error_code": 0,
         *   "timestamp": 1617332994
         * }
         */
        JSONObject res=client.search(image,imageType,groupIdList, options);
        /**
         * {
         *   "result": {
         *     "face_token": "cd0a881bb9e901dc0613970ae411a1c7",
         *     "user_list": [{
         *       "score": 93.64924621582,
         *       "group_id": "java2003",
         *       "user_id": "user3",
         *       "user_info": ""
         *     }]
         *   },
         *   "log_id": 7935001552011,
         *   "error_msg": "SUCCESS",
         *   "cached": 0,
         *   "error_code": 0,
         *   "timestamp": 1617332994
         * }
         */
        try {
            if ("SUCCESS".equals(res.getString("error_msg"))){
                 /*
            如下json数组，每一个元素都有一个score，必须要找到
            score最大的那个jsonObject，返回这个jsonObject的user_id属性的值。
            例如输入如下内容：
            [{
                 "score": 93.64924621582,
                 "group_id": "java2003",
                 "user_id": "user3",
                 "user_info": ""
            },
            {
                 "score": 92.56897879798,
                 "group_id": "java2003",
                 "user_id": "user4",
                 "user_info": ""
            }]
            输出：user3
         */
                JSONArray userList=res.getJSONObject("result").getJSONArray("user_list");
                if (userList!=null&&userList.length()>0){
                    double score=-1;
                    Long uid=null;
                    for (int i = 0; i <userList.length() ; i++) {
                        JSONObject userInfo=userList.getJSONObject(i);
                        if (userInfo.getDouble("score")>score){
                            score=userInfo.getDouble("score");
                            uid=Long.parseLong(userInfo.getString("user_id").substring(4));
                        }
                    }
                    return uid;
                }else {
                    return null;
                }
            }else {
                return null;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args)  {
        String fileName1="E:\\TEST\\glnz.jpg";
        String fileName2="E:\\TEST\\glnz1.jpg";
        boolean one = isOne(fileName1, fileName2,1);
        if (one){
            System.out.println("是一个人");
        }else {
            System.out.println("不是一个人");
        }
    }



}
